package com.qihang.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * 
 * 本类是通过ip获取地理位置信息的工具类
 * 主要通过ip地址来获取地理信息位置,本类中可以通过HttpServeletRequest获取ip地址，然后再通过ip地址获取地理信息位置
 * 使用方法：获取客户端ip：GetAddressByIp.getIpAddr(request)    获取客户端地理位置信息：getAddressByIP(String ip)
 *
 *
 */
public class GetAddressByIp {
    /**
     * 获取客户端IP地址
     * 
     * @param request "请求"作为参数
     * @return 通过"请求"获取的ip地址
     */
//    public static String getIpAddr(HttpServletRequest request) {
//        String ip = request.getHeader("x-forwarded-for");
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddr();
//        }
//        return ip;
//    }

    /**
     * 根据IP地址获取地理位置
     * 
     * @param ip ip地址
     * @return ip地址对应的地理信息位置
     */
    public static String getAddressByIP(String ip) {
        Pattern pattern = Pattern.compile("(\\d{1,3}\\.){3}\\d{1,3}");
        if (!pattern.matcher(ip).matches()) {
            return "无效的ip地址";
        }
        try {
            URL url = new URL("http://www.ip138.com/ips138.asp?ip=" + ip);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "GBK"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            ip = result.substring(result.indexOf("主数据：") + 4,
                    result.indexOf("</li><li>参考数据"));
            char[] ipStr = ip.toCharArray();
            System.out.println(ipStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }
    
    /**
	 * 获取IP地址
	 * 
	 * @param request
	 * @return
	 */	
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
